"""
重构后的主应用文件
使用模块化架构，提高代码可维护性
"""

from math import log
from fastapi import FastAPI, BackgroundTasks, UploadFile, File
from cachetools import TTLCache
import uuid
import time
import logging

# 导入新模块
from .func.models import ImageCheckRequest, CheckResult, UploadCheckResult
from .func.config_manager import config
from .func.banner import print_startup_banner
from .func.rule_manager import RULES
from .services.ai_services import get_ai_service
from .func.api_handlers import APIHandler
from .logging_config import setup_logging

# --- 初始化服务 ---
logger = logging.getLogger(__name__)

# 初始化缓存
app_settings = config.get('app_settings', {})
analysis_cache = TTLCache(maxsize=app_settings.get('cache_max_size', 1000),
                         ttl=app_settings.get('cache_ttl_seconds', 3600))

# 初始化AI服务
try:
    ai_service = get_ai_service(config)
except ValueError as e:
    logger.fatal(f"AI Service initialization failed: {e}")
    exit(1)

# 初始化API处理器
api_handler = APIHandler(config, RULES)

# 创建FastAPI应用
app = FastAPI(title="图片内容检查服务", version="1.1")

# --- API端点 ---

@app.post("/api/v1/check-image", response_model=CheckResult)
async def check_image(request: ImageCheckRequest):
    """
    检查图片中是否包含违规内容 (通过URL)
    """
    return await api_handler.process_url_image(request.image_url, analysis_cache)

@app.post("/api/v1/check-image-upload", response_model=UploadCheckResult)
async def check_image_upload(file: UploadFile = File(...)):
    """
    通过文件上传检查图片中是否包含违规内容
    """
    # 验证文件类型
    if not file.content_type or not file.content_type.startswith('image/'):
        from fastapi import HTTPException
        raise HTTPException(status_code=400, detail="请上传有效的图片文件")

    # 读取文件内容
    file_content = await file.read()

    return await api_handler.process_upload_image(file_content, file.filename)

# --- 启动事件 ---

@app.on_event("startup")
async def startup_event():
    """应用启动时的事件处理"""
    # 初始化日志系统
    loggers = setup_logging()
    logger.info("UBBC日志系统已初始化")

    print_startup_banner(config)

    # 启动Web管理界面
    import threading
    import uvicorn
    from .web_admin import web_app

    def start_web_admin():
        web_port = int(config['server']['web-port'])
        host = config['server']['host']
        print(f"🌐 启动Web管理界面: http://{host}:{web_port}")
        uvicorn.run(web_app, host=host, port=web_port)

    # 在后台线程启动Web管理界面
    web_thread = threading.Thread(target=start_web_admin, daemon=True)
    web_thread.start()

# --- 主执行块 ---

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host=config['server']['host'], port=int(config['server']['port']))
